C dereference pointer

As we already know that "what is a pointer", a pointer is a variable that stores the address of another variable. The dereference operator is also known as an indirection operator, which is represented by (*). When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a pointer. When we dereference a pointer, then the value of the variable pointed by this pointer will be returned.

Why we use dereferencing pointer?

Dereference a pointer is used because of the following reasons:

Let's observe the following steps to dereference a pointer.

The above line changes the value of 'x' variable from 9 to 8 because 'ptr' points to the 'x' location and dereferencing of 'ptr', i.e., *ptr=8 will update the value of x.

Let's combine all the above steps:

            
                #include   
                    int main()  
                    {  
                        int x=9;  
                        int *ptr;  
                        ptr=&x;  
                        *ptr=8;  
                        printf("value of x is : %d", x);  
                        return 0;}  
            
                    

Output

Let's consider another example.

                
                    #include   
                        int main()  
                        {  
                            int x=4;  
                            int y;  
                            int *ptr;  
                            ptr=&x;   
                            y=*ptr;  
                            *ptr=5;  
                            printf("The value of x is : %d",x);  
                            printf("n The value of y is : %d",y);  
                            return 0;  
                        }   
                
                        

In the above code:

Output

Let's consider another scenario.

                    
                        #include   
                            int main()  
                            {  
                               int a=90;  
                               int *ptr1,*ptr2;  
                               ptr1=&a;  
                               ptr2=&a;  
                               *ptr1=7;  
                               *ptr2=6;  
                                printf("The value of a is : %d",a);  
                                return 0;  
                            }    
                    
                            

In the above code:

Output